package com.cookie.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cookie.common.utils.Result;
import com.cookie.entity.User;
import com.cookie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : cookie ✌️
 * @date : 2018/10/1 9:21
 */
@RestController
@RequestMapping("wx/api/user")
@Slf4j
public class ApiUserController {

    @Autowired
    private UserService userService;

    @PostMapping("save")
    public Result save(User user) {
        User user1 = userService.selectOne(new EntityWrapper<User>().eq("open_id", user.getOpenId()));
        if (user1 != null) {
            log.info("用户已存在");
            return Result.ok();
        }
        user.setUsername(user.getNickName());
        boolean flag = userService.insert(user);
        if (flag) {
            log.info("用户成功保存【{}】", user);
            return Result.ok();
        }
        log.info("用户保存失败【{}】", user);
        return Result.error(1, "fail");
    }

    @GetMapping("queryByOpenId")
    public Result queryByOpenId(String openId) {
        User user = userService.selectOne(new EntityWrapper<User>().eq("open_id", openId));
        String s = JSON.toJSONString(user,  SerializerFeature.WriteNullStringAsEmpty);
        return Result.ok(s);
    }
}
